package cn.zyb.org.service.impl;

import cn.zyb.basic.service.Impl.BaseServiceImpl;
import cn.zyb.org.domain.Department;
import cn.zyb.org.mapper.DepartmentMapper;
import cn.zyb.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 业务实现类：部门
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Transactional
    @Override
    public void add(Department department) {
      //情况1：不选 -> parent_id=null
      //情况2：选了清空 -> parent_id=null
      //情况3：选上级部门 -> parent_id=6[上级部门]

      departmentMapper.save(department);

      //如果没有选中上级部门就加自己的id
      if(department.getParent_id()==null){
        department.setDirPath("/"+department.getId());
      }else{//如果选了上级部门
        //根据父id查询它的dirPath
        String parentDirPath = departmentMapper.loadById(department.getParent_id()).getDirPath();
        //再将父部门的dirPath与自己的id进行拼接
        department.setDirPath(parentDirPath+"/"+department.getId());
      }
      departmentMapper.update(department);
    }


    @Transactional
    @Override
    public void update(Department department) {
      //如果没有选中上级部门就加自己的id
      if(department.getParent_id()==null){
        department.setDirPath("/"+department.getId());
      }else{//如果选了上级部门
        //根据父id查询它的dirPath
        String parentDirPath = departmentMapper.loadById(department.getParent_id()).getDirPath();
        //再将父部门的dirPath与自己的id进行拼接
        department.setDirPath(parentDirPath+"/"+department.getId());
      }

      departmentMapper.update(department);
    }
  @Override
  public List<Department> deptTree() {
    List<Department> departments = departmentMapper.loadAll();
    Map<Long,Department> map = new HashMap<>();
    for (Department department : departments) {
      map.put(department.getId(),department);
    }
    List<Department> deptTree = new ArrayList<>();
    for (Department department : departments) {
      if(department.getParent_id() == null){//顶级部门
        deptTree.add(department);
      }else{//不是顶级部门
        //获取当前部门的上级部门id
        Long parent_id = department.getParent_id();
        //上级部门对象
        Department parentDepartment = map.get(parent_id);
        //将自己装在上级部门的集合中
        parentDepartment.getChildren().add(department);
      }
    }
    return deptTree;
  }
}
